// index.js
const app = getApp()

Page({
  data: {
    previewImage: '',
    isProcessing: false,
    correctionResults: []
  },

  onLoad() {
    // 页面加载时的初始化
  },

  // 开始批改 - 调用相机拍照
  startCorrection() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      camera: 'back',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        this.setData({
          previewImage: tempFilePath
        })
      },
      fail: (err) => {
        console.error('拍照失败:', err)
        wx.showToast({
          title: '拍照失败',
          icon: 'error'
        })
      }
    })
  },

  // 从相册选择图片
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        this.setData({
          previewImage: tempFilePath
        })
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        wx.showToast({
          title: '选择图片失败',
          icon: 'error'
        })
      }
    })
  },

  // 预览图片
  previewImage() {
    if (this.data.previewImage) {
      wx.previewImage({
        urls: [this.data.previewImage]
      })
    }
  },

  // 重新拍照
  retakePhoto() {
    this.setData({
      previewImage: ''
    })
  },

  // 处理图片 - OCR识别和口算批改
  processImage() {
    if (!this.data.previewImage) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'none'
      })
      return
    }

    this.setData({
      isProcessing: true
    })

    // 使用真实OCR识别（华为云）
    this.performRealOCRRecognition()
  },

  // 模拟OCR识别过程
  simulateOCRRecognition() {
    // 这里应该调用真实的OCR API
    // 目前使用模拟数据演示功能
    
    setTimeout(() => {
      // 模拟识别到的口算题目
      const mockResults = this.generateMockResults()
      
      this.setData({
        isProcessing: false,
        correctionResults: mockResults
      })

      // 跳转到结果页面
      wx.navigateTo({
        url: '/pages/result/result',
        success: (res) => {
          res.eventChannel.emit('acceptDataFromOpenerPage', {
            results: mockResults,
            originalImage: this.data.previewImage
          })
        }
      })
    }, 3000) // 模拟3秒处理时间
  },

  // 真实OCR识别过程（使用华为云OCR）
  async performRealOCRRecognition() {
    try {
      // 将图片转换为Base64
      const imageBase64 = await this.imageToBase64(this.data.previewImage)
      
      // 调用华为云OCR
      const huaweiOCR = require('../../utils/huawei-ocr.js')
      const ocrResults = await huaweiOCR.recognizeText(imageBase64)
      
      console.log('OCR识别结果:', ocrResults)
      
      // 提取口算题目
      const mathProblems = huaweiOCR.extractMathProblems(ocrResults)
      
      console.log('提取的数学题目:', mathProblems)
      
      // 批改口算题目
      const correctionResults = huaweiOCR.gradeMathProblems(mathProblems)
      
      console.log('批改结果:', correctionResults)
      
      this.setData({
        isProcessing: false,
        correctionResults: correctionResults
      })

      // 跳转到结果页面
      wx.navigateTo({
        url: '/pages/result/result',
        success: (res) => {
          res.eventChannel.emit('acceptDataFromOpenerPage', {
            results: correctionResults,
            originalImage: this.data.previewImage
          })
        }
      })
    } catch (error) {
      console.error('OCR识别失败:', error)
      this.setData({
        isProcessing: false
      })
      wx.showToast({
        title: '识别失败，请重试',
        icon: 'error'
      })
    }
  },

  // 图片转Base64
  imageToBase64(filePath) {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath: filePath,
        encoding: 'base64',
        success: (res) => {
          resolve(res.data)
        },
        fail: (error) => {
          console.error('图片转Base64失败:', error)
          reject(error)
        }
      })
    })
  },

  // 生成模拟的批改结果
  generateMockResults() {
    return [
      {
        id: 1,
        question: "12 + 8 = 20",
        userAnswer: "20",
        correctAnswer: "20",
        isCorrect: true,
        confidence: 0.95,
        position: { x: 50, y: 100, width: 200, height: 40 }
      },
      {
        id: 2,
        question: "15 - 7 = 8",
        userAnswer: "9",
        correctAnswer: "8",
        isCorrect: false,
        confidence: 0.92,
        position: { x: 50, y: 160, width: 200, height: 40 }
      },
      {
        id: 3,
        question: "6 × 9 = 54",
        userAnswer: "54",
        correctAnswer: "54",
        isCorrect: true,
        confidence: 0.88,
        position: { x: 50, y: 220, width: 200, height: 40 }
      },
      {
        id: 4,
        question: "24 ÷ 3 = 8",
        userAnswer: "7",
        correctAnswer: "8",
        isCorrect: false,
        confidence: 0.75, // 低置信度，标记为"疑是错误"
        position: { x: 50, y: 280, width: 200, height: 40 }
      },
      {
        id: 5,
        question: "11 + 19 = 30",
        userAnswer: "30",
        correctAnswer: "30",
        isCorrect: true,
        confidence: 0.96,
        position: { x: 50, y: 340, width: 200, height: 40 }
      }
    ]
  },

  // 真实OCR识别函数（需要接入第三方API）
  async performOCRRecognition(imagePath) {
    try {
      // 这里应该调用真实的OCR API，比如百度OCR、腾讯OCR等
      // 示例代码：
      /*
      const result = await wx.request({
        url: 'YOUR_OCR_API_ENDPOINT',
        method: 'POST',
        data: {
          image: imagePath,
          // 其他参数
        },
        header: {
          'content-type': 'application/json',
          'Authorization': 'YOUR_API_KEY'
        }
      })
      return result.data
      */
      
      // 目前返回模拟数据
      return this.generateMockResults()
    } catch (error) {
      console.error('OCR识别失败:', error)
      throw error
    }
  },

  // 口算题目解析和计算
  parseAndCalculate(questionText) {
    // 解析口算题目，提取数字和运算符
    const regex = /(\d+)\s*([+\-×÷])\s*(\d+)\s*=\s*(\d+)/
    const match = questionText.match(regex)
    
    if (!match) {
      return null
    }

    const [, num1, operator, num2, userAnswer] = match
    let correctAnswer

    switch (operator) {
      case '+':
        correctAnswer = parseInt(num1) + parseInt(num2)
        break
      case '-':
        correctAnswer = parseInt(num1) - parseInt(num2)
        break
      case '×':
        correctAnswer = parseInt(num1) * parseInt(num2)
        break
      case '÷':
        correctAnswer = parseInt(num1) / parseInt(num2)
        break
      default:
        return null
    }

    return {
      question: `${num1} ${operator} ${num2} = ${userAnswer}`,
      userAnswer: parseInt(userAnswer),
      correctAnswer: correctAnswer,
      isCorrect: parseInt(userAnswer) === correctAnswer
    }
  },

    // 调试华为云OCR
  async debugHuaweiOCR() {
    try {
      wx.showLoading({
        title: '正在调试...'
      })

      const huaweiDebugger = require('../../utils/huawei-ocr-debug.js')
      const workingEndpoint = await huaweiDebugger.runDiagnostics()

      wx.hideLoading()

      wx.showModal({
        title: '调试完成',
        content: `华为云OCR API调试成功！\n推荐端点: ${workingEndpoint}`,
        showCancel: false
      })

      // 如果调试成功，可以启用真实OCR
      console.log('调试成功，可以启用真实OCR调用')
    } catch (error) {
      wx.hideLoading()

      wx.showModal({
        title: '调试失败',
        content: `华为云OCR API调试失败:\n${error.message}`,
        showCancel: false
      })

      console.error('华为云OCR调试失败:', error)
    }
  },

  // 简化测试华为云OCR
  async testSimpleOCR() {
    try {
      wx.showLoading({
        title: '正在测试...'
      })

      const simpleTester = require('../../utils/huawei-ocr-simple.js')
      const result = await simpleTester.runFullTest()

      wx.hideLoading()

      wx.showModal({
        title: '测试完成',
        content: '简化测试完成，请查看控制台日志',
        showCancel: false
      })

      console.log('简化测试完成:', result)
    } catch (error) {
      wx.hideLoading()

      wx.showModal({
        title: '测试失败',
        content: `简化测试失败:\n${error.message}`,
        showCancel: false
      })

      console.error('简化测试失败:', error)
    }
  },

  // 检查Token状态
  checkTokenStatus() {
    try {
      const tokenManager = require('../../utils/token-manager.js')
      const status = tokenManager.getTokenStatus()
      
      console.log('Token状态:', status)
      
      let content = `Token状态:\n`
      content += `有Token: ${status.hasToken ? '是' : '否'}\n`
      content += `有效: ${status.isValid ? '是' : '否'}\n`
      content += `剩余时间: ${status.remainingMinutes}分钟\n`
      content += `正在刷新: ${status.isRefreshing ? '是' : '否'}\n`
      if (status.expireTime) {
        content += `过期时间: ${status.expireTime}`
      }

      wx.showModal({
        title: 'Token状态',
        content: content,
        showCancel: false
      })
    } catch (error) {
      wx.showModal({
        title: '错误',
        content: `获取Token状态失败:\n${error.message}`,
        showCancel: false
      })
    }
  },

  // Token调试
  async debugToken() {
    try {
      wx.showLoading({
        title: '正在调试Token...'
      })

      const tokenDebugger = require('../../utils/token-debug.js')
      const token = await tokenDebugger.runFullDebug()

      wx.hideLoading()

      wx.showModal({
        title: 'Token调试成功',
        content: `Token获取成功！\nToken: ${token.substring(0, 20)}...`,
        showCancel: false
      })

      console.log('Token调试成功:', token.substring(0, 20) + '...')
    } catch (error) {
      wx.hideLoading()

      wx.showModal({
        title: 'Token调试失败',
        content: `Token调试失败:\n${error.message}`,
        showCancel: false
      })

      console.error('Token调试失败:', error)
    }
  },

  // 网络诊断
  async debugNetwork() {
    try {
      wx.showLoading({
        title: '正在诊断网络...'
      })

      const networkDebugger = require('../../utils/network-debug.js')
      const diagnosis = await networkDebugger.runFullDiagnosis()

      wx.hideLoading()

      // 分析诊断结果
      let content = '网络诊断完成\n\n'
      
      // 基本网络连接结果
      const successfulConnections = diagnosis.networkResults.filter(r => r.success).length
      content += `基本连接: ${successfulConnections}/${diagnosis.networkResults.length} 成功\n`
      
      // Token请求结果
      if (diagnosis.tokenResults.success) {
        content += `Token请求: 成功\n`
        content += `状态码: ${diagnosis.tokenResults.statusCode}\n`
        content += `有响应头: ${diagnosis.tokenResults.hasHeader ? '是' : '否'}\n`
      } else {
        content += `Token请求: 失败\n`
        content += `错误: ${diagnosis.tokenResults.error}\n`
      }
      
      // 网络类型
      content += `网络类型: ${diagnosis.networkType}\n`
      
      // 是否在开发工具中
      content += `开发工具: ${diagnosis.config.isDevTools ? '是' : '否'}`

      wx.showModal({
        title: '网络诊断结果',
        content: content,
        showCancel: false
      })

      console.log('网络诊断完成:', diagnosis)
    } catch (error) {
      wx.hideLoading()

      wx.showModal({
        title: '网络诊断失败',
        content: `网络诊断失败:\n${error.message}`,
        showCancel: false
      })

      console.error('网络诊断失败:', error)
    }
  },

  // 配置检查
  async checkConfig() {
    try {
      wx.showLoading({
        title: '正在检查配置...'
      })

      const configChecker = require('../../utils/config-checker.js')
      const checkResult = configChecker.runFullCheck()
      const suggestions = configChecker.generateFixSuggestions(checkResult)

      wx.hideLoading()

      // 生成配置检查结果
      let content = '配置检查完成\n\n'
      
      // 系统信息
      if (checkResult.systemInfo.success) {
        content += `平台: ${checkResult.systemInfo.platform}\n`
        content += `基础库: ${checkResult.systemInfo.SDKVersion}\n`
        content += `开发工具: ${checkResult.systemInfo.isDevTools ? '是' : '否'}\n\n`
      }
      
      // 项目配置
      if (checkResult.projectConfig.success) {
        const setting = checkResult.projectConfig.setting
        content += `域名校验: ${setting && !setting.urlCheck ? '已关闭' : '已开启'}\n\n`
      }
      
      // 修复建议
      content += '修复建议:\n'
      suggestions.forEach(suggestion => {
        content += `${suggestion}\n`
      })

      wx.showModal({
        title: '配置检查结果',
        content: content,
        showCancel: false
      })

      console.log('配置检查完成:', checkResult)
      console.log('修复建议:', suggestions)
    } catch (error) {
      wx.hideLoading()

      wx.showModal({
        title: '配置检查失败',
        content: `配置检查失败:\n${error.message}`,
        showCancel: false
      })

      console.error('配置检查失败:', error)
    }
  },

  // Token提取测试
  async extractToken() {
    try {
      wx.showLoading({
        title: '正在提取Token...'
      })

      // 先获取Token响应
      const tokenUrl = 'https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens'
      const tokenRequest = {
        auth: {
          identity: {
            methods: ['password'],
            password: {
              user: {
                name: 'ilieyun',
                password: 'Lieyun@2090',
                domain: {
                  name: 'ilieyun'
                }
              }
            }
          },
          scope: {
            project: {
              name: 'cn-north-4'
            }
          }
        }
      }

      console.log('=== 发送Token请求 ===')
      console.log('请求URL:', tokenUrl)
      console.log('请求体:', JSON.stringify(tokenRequest, null, 2))
      
      // 使用回调方式而不是await
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: tokenUrl,
          method: 'POST',
          data: tokenRequest,
          header: {
            'Content-Type': 'application/json'
          },
          timeout: 15000,
          success: (res) => {
            console.log('=== 收到响应 ===')
            console.log('完整响应对象:', res)
            console.log('响应对象类型:', typeof res)
            console.log('响应对象键名:', Object.keys(res))
            console.log('响应状态码:', res.statusCode)
            console.log('响应状态:', res.status)
            console.log('响应数据:', res.data)
            console.log('响应头:', res.header)
            console.log('响应头类型:', typeof res.header)
            console.log('响应头是否为null:', res.header === null)
            console.log('响应头是否为undefined:', res.header === undefined)
            resolve(res)
          },
          fail: (err) => {
            console.log('请求失败:', err)
            reject(err)
          }
        })
      })

      // 使用Token提取工具
      const tokenExtractor = require('../../utils/token-extractor.js')
      const result = tokenExtractor.extractToken(response)

      wx.hideLoading()

      if (result.success) {
        wx.showModal({
          title: 'Token提取成功',
          content: `提取方法: ${result.method}\n键名: ${result.key}\nToken: ${result.token.substring(0, 20)}...`,
          showCancel: false
        })
        console.log('Token提取成功:', result)
      } else {
        wx.showModal({
          title: 'Token提取失败',
          content: `所有提取方法都失败了\n请查看控制台日志`,
          showCancel: false
        })
        console.log('Token提取失败:', result)
      }
    } catch (error) {
      wx.hideLoading()

      wx.showModal({
        title: 'Token提取失败',
        content: `Token提取失败:\n${error.message}`,
        showCancel: false
      })

      console.error('Token提取失败:', error)
    }
  },

  // 简单请求测试
  async simpleRequestTest() {
    try {
      wx.showLoading({
        title: '正在测试网络请求...'
      })

      const simpleTester = require('../../utils/simple-request-test.js')
      const results = await simpleTester.runAllTests()

      wx.hideLoading()

      // 分析结果
      let content = '网络请求测试完成\n\n'
      
      results.forEach((result, index) => {
        content += `测试${index + 1} (${result.method}):\n`
        if (result.success) {
          content += `✅ 成功\n`
          content += `状态码: ${result.statusCode}\n`
          if (result.header) {
            content += `有响应头: 是\n`
          }
        } else {
          content += `❌ 失败\n`
          content += `错误: ${result.error}\n`
        }
        content += '\n'
      })

      wx.showModal({
        title: '网络请求测试结果',
        content: content,
        showCancel: false
      })

      console.log('简单请求测试完成:', results)
    } catch (error) {
      wx.hideLoading()

      wx.showModal({
        title: '测试失败',
        content: `测试失败:\n${error.message}`,
        showCancel: false
      })

             console.error('简单请求测试失败:', error)
     }
   },

   // OCR格式调试
   async debugOCRFormats() {
     try {
       wx.showLoading({
         title: '正在调试OCR格式...'
       })

       const ocrDebugger = require('../../utils/huawei-ocr-debug.js')
       const results = await ocrDebugger.runFullDebug()

       wx.hideLoading()

       // 分析结果
       let content = 'OCR格式调试完成\n\n'
       
       // 格式测试结果
       const successfulFormats = results.formatTests.filter(r => r.success).length
       content += `格式测试: ${successfulFormats}/${results.formatTests.length} 成功\n`
       
       // 图片格式测试结果
       const successfulImages = results.imageTests.filter(r => r.success).length
       content += `图片格式: ${successfulImages}/${results.imageTests.length} 成功\n\n`
       
       // 显示成功的格式
       const successfulTests = [...results.formatTests, ...results.imageTests].filter(r => r.success)
       if (successfulTests.length > 0) {
         content += '成功的格式:\n'
         successfulTests.forEach(test => {
           content += `• ${test.name}\n`
         })
       } else {
         content += '没有找到成功的格式\n'
         content += '请查看控制台日志了解详细错误'
       }

       wx.showModal({
         title: 'OCR格式调试结果',
         content: content,
         showCancel: false
       })

       console.log('OCR格式调试完成:', results)
     } catch (error) {
       wx.hideLoading()

       wx.showModal({
         title: 'OCR格式调试失败',
         content: `调试失败:\n${error.message}`,
         showCancel: false
       })

       console.error('OCR格式调试失败:', error)
     }
   },
   
   // 快速OCR测试
   async runQuickOcrTest() {
     try {
       wx.showLoading({
         title: '正在快速测试...'
       })

       const quickOcrTest = require('../../utils/quick-ocr-test.js')
       await quickOcrTest.test()

       wx.hideLoading()

       wx.showModal({
         title: '快速测试完成',
         content: '快速OCR测试完成，请查看控制台日志',
         showCancel: false
       })

       console.log('快速OCR测试完成')
     } catch (error) {
       wx.hideLoading()

       wx.showModal({
         title: '快速测试失败',
         content: `测试失败:\n${error.message}`,
         showCancel: false
       })

       console.error('快速OCR测试失败:', error)
     }
   },

  // 测试数学计算功能
  testMathCalculations() {
    const huaweiOCR = require('../../utils/huawei-ocr.js')
    huaweiOCR.testMathCalculations()
    
    wx.showToast({
      title: '测试完成，查看控制台',
      icon: 'none'
    })
  },

  // 测试图片标注功能
  testImageAnnotation() {
    wx.showToast({
      title: '请拍照测试标注功能',
      icon: 'none'
    })
    
    // 模拟一些测试数据
    const testResults = [
      {
        id: 1,
        type: 'basic',
        question: '12 + 8 = 20',
        userAnswer: 20,
        correctAnswer: 20,
        answerComparison: '20',
        isCorrect: true,
        confidence: 0.95,
        position: { x: 50, y: 100, width: 200, height: 40 }
      },
      {
        id: 2,
        type: 'basic',
        question: '15 - 7 = 8',
        userAnswer: 9,
        correctAnswer: 8,
        answerComparison: '8',
        isCorrect: false,
        confidence: 0.92,
        position: { x: 50, y: 160, width: 200, height: 40 }
      },
      {
        id: 3,
        type: 'division_with_remainder',
        question: '25 ÷ 4 = 6...1',
        userAnswer: { quotient: 6, remainder: 2 },
        correctAnswer: { quotient: 6, remainder: 1 },
        answerComparison: '商: 6, 余数: 1',
        isCorrect: false,
        confidence: 0.75,
        position: { x: 50, y: 220, width: 200, height: 40 }
      }
    ]
    
    // 保存测试数据到本地存储
    wx.setStorageSync('testResults', testResults)
    
    wx.showModal({
      title: '测试数据已准备',
      content: '测试数据已保存，请拍照测试图片标注功能',
      showCancel: false,
      success: () => {
        // 可以跳转到结果页面进行测试
        console.log('测试数据已准备:', testResults)
      }
    })
  }
})
